home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 6430 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How to check array lenght?
  5. Date: Sat, 24 Feb 96 20:12:23 GMT
  6. Organization: none
  7. Message-ID: <825192743snz@genesis.demon.co.uk>
  8. References: <4gbphl$ht@malakor.kku.ac.th> <Pine.A32.3.91.960221002504.156335H-100000@black.weeg.uiowa.edu> <4ggmfs$tg@dopey.magg.net>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <4ggmfs$tg@dopey.magg.net> n4mwd@magg.net "Dennis Hawkins" writes:
  15.  
  16. >The Amorphous Mass <robinson@blue.weeg.uiowa.edu> wrote:
  17. >
  18. >>On 20 Feb 1996, terdthai tong-un wrote:
  19. >
  20. >>> In subroutine that recieve pointer of array.
  21. >>> How to check number of multidimention array in that routine?
  22. >
  23. >>  You can't.  That information would have to be passed to the function 
  24. >>via extra parameters or some other means.
  25. >Try using: 
  26. >
  27. >#define numelem(array)   (sizeof(array) / sizeof(array[0]))
  28. >
  29. >then pass the results as an extra parameter to your function.
  30.  
  31. To see why this is necessary consider:
  32.  
  33. void foo(int array[])
  34. {
  35.     int i;
  36.  
  37.     printf("%lu\n", (unsigned long) sizeof array);
  38.  
  39.     array = &i;
  40. }
  41.  
  42. By the rewrite rule for function parameters the prototype is treated exactly
  43. as it it were written as:
  44.  
  45. void foo(int *array)
  46.  
  47. So the value that gets printed is always the value of sizeof(int *) however
  48. the function was called. Although array looks like an array according to its
  49. declaration it is truely a pointer and behaves precisely like one (e.g.
  50. you can assign to it as in the example).
  51.  
  52. Your define is good when simply passed an array name. However it could
  53. be improved simply to cope with any array-valued expression:
  54.  
  55. #define numelem(array)   (sizeof(array) / sizeof((array)[0]))
  56.  
  57. or
  58.  
  59. #define numelem(array)   (sizeof(array) / sizeof *(array))
  60.  
  61. which has the benefit of being able to correctly reject a type as the
  62. macro argument.
  63.  
  64. These are safe against expressions with side-effects since sizeof doesn't
  65. evaluate its operand.
  66.  
  67. -- 
  68. -----------------------------------------
  69. Lawrence Kirby | fred@genesis.demon.co.uk
  70. Wilts, England | 70734.126@compuserve.com
  71. -----------------------------------------
  72.